<template>
  <div class="container">
    <div class="header">
      <div class="title">管理员列表</div>
      <!-- 省份选择下拉框 -->
      <el-select  size="medium" filterable v-model="province_id" placeholder="请选择省份" @change="handleChangeProvince" clearable>
        <el-option
                v-for="(province, index) in provinceArr"
                :key="index"
                :label="province.name"
                :value="province.id">
        </el-option>
      </el-select>
      <!-- 城市选择下拉框 -->
      <el-select  size="medium" filterable v-model="city_id" placeholder="请选择城市" @change="handleChangeCity" clearable>
        <el-option
                v-for="(city, index) in cityArr"
                :key="index"
                :label="city.name"
                :value="city.id">
        </el-option>
      </el-select>
      <!-- 区/县选择下拉框 -->
      <el-select  size="medium" filterable v-model="county_id" placeholder="请选择地区" @change="handleChangeCounty" clearable>
        <el-option
          v-for="(county, index) in countyArr"
          :key="index"
          :label="county.name"
          :value="county.id">
        </el-option>
      </el-select>
    </div>
    <!-- 表格 -->
    <lin-table
      :tableColumn="tableColumn"
      :tableData="tableData"
      :operate="operate"
      @handleEdit="handleEdit"
      @handleDelete="handleDelete"
      @row-click="rowClick"
      v-loading="loading"></lin-table>
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        @current-change="handleCurrentChange"
        :background="true"
        :page-size="pageCount"
        :current-page="currentPage"
        v-if="refreshPagination"
        layout="prev, pager, next, jumper"
        :total="total_nums">
      </el-pagination>
    </div>
    <!-- 弹窗 -->
    <el-dialog :append-to-body="true" :before-close="handleClose" :visible.sync="dialogFormVisible">
      <div style="margin-top:-25px;">
        <el-tabs v-model="activeTab" @tab-click="handleClick">
          <el-tab-pane label="修改信息" name="修改信息">
            <user-info
              ref="userInfo"
              v-if="dialogFormVisible"
              @handleInfoResult="handleInfoResult"
              labelPosition="right"
              pageType="edit"
              :id="id"
              :groups="groups"
              :info="form"
              :submit="false"
              class="info" />
          </el-tab-pane>
          <el-tab-pane label="修改密码" name="修改密码">
            <user-password
              @handlePasswordResult="handlePasswordResult"
              ref="password"
              :id="id"
              class="password" />
          </el-tab-pane>
        </el-tabs>
      </div>
      <!-- 按键操作 -->
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmEdit">确 定</el-button>
        <el-button @click="resetForm">重 置</el-button>

      </div>
    </el-dialog>
  </div>
</template>

<script>
import Admin from '@/lin/models/admin'
import LinTable from '@/components/base/table/lin-table'
import UserInfo from './UserInfo'
import UserPassword from './UserPassword'
import province from '@/models/province'
import city from '@/models/city'
import county from '@/models/county'

export default {
  components: { LinTable, UserInfo, UserPassword },
  inject: ['eventBus'],
  data() {
    return {
      id: 0, // 用户id
      refreshPagination: true, // 页数增加的时候，因为缓存的缘故，需要刷新Pagination组件
      editIndex: null, // 编辑的行
      total_nums: 0, // 分组内的用户总数
      currentPage: 1, // 默认获取第一页的数据
      pageCount: 10, // 每页10条数据
      tableData: [], // 表格数据
      tableColumn: [], // 表头数据
      operate: [], // 表格按键操作区
      dialogFormVisible: false, // 控制弹窗显示
      selectGroup: '', // 选中的分组Id
      groups: [], // 所有分组
      provinceArr: [], // 所有省份
      province_id: '', // 搜索的省份ID
      cityArr: [], // 根据省份选择城市
      city_id: '', // 搜索的城市ID
      countyArr: [], // 根据城市选择区县
      county_id: '', // 搜索的区县ID
      group_id: undefined,
      activeTab: '修改信息',
      form: { // 表单信息
        username: '',
        password: '',
        confirm_password: '',
        email: '',
        group_id: '',
        province_id: '',
        city_id: '',
        county_id: '',
        explain: '',
      },
      loading: false,
    }
  },
  methods: {
    // 根据分组 刷新/获取分组内的用户
    async getAdminUsers() {
      let res
      const currentPage = this.currentPage - 1
      try {
        this.loading = true
        res = await Admin.getAdminUsers({
          group_id: this.group_id,
          count: this.pageCount,
          page: currentPage,
          province_id: this.province_id,
          city_id: this.city_id,
          county_id: this.county_id,
        }) // eslint-disable-line
        this.loading = false
        this.tableData = [...res.items]
        this.total_nums = res.total
      } catch (e) {
        this.loading = false
        console.log(e)
      }
    },
    // 获取所有分组
    async getAllGroups() {
      try {
        this.loading = true
        this.groups = await Admin.getAllGroups()
        this.loading = false
      } catch (e) {
        this.loading = false
        console.log(e)
      }
    },
    // 获取所拥有的权限并渲染  由子组件提供
    async handleEdit(val) {
      this.editIndex = val.index
      let selectedData
      // 单击 编辑按键
      if (val.index >= 0) {
        selectedData = val.row
      } else {
        // 单击 table row
        selectedData = val
      }
      this.id = selectedData.id
      this.form.username = selectedData.username
      this.form.email = selectedData.email
      this.form.group_id = selectedData.group_id
      this.form.province_id = selectedData.province_id
      this.form.city_id = selectedData.city_id
      this.form.county_id = selectedData.county_id
      this.form.explain = selectedData.explain
      this.dialogFormVisible = true
    },
    // 下拉框选择分组
    async handleChange() {
      this.currentPage = 1
      this.loading = true
      await this.getAdminUsers()
      this.loading = false
    },
    // 下拉框选择省份
    async handleChangeProvince() {
      this.currentPage = 1
      this.loading = true
      await this.getAdminUsers()
      this.loading = false
      this.city_id = ''
      this.county_id = ''
      this.getCityAll()
    },
    // 下拉框选择城市
    async handleChangeCity() {
      this.currentPage = 1
      this.loading = true
      await this.getAdminUsers()
      this.loading = false
      this.county_id = ''
      this.getCountyAll()
    },
    // 下拉框选择区/县
    async handleChangeCounty() {
      this.currentPage = 1
      this.loading = true
      await this.getAdminUsers()
      this.loading = false
    },
    // 切换table页
    async handleCurrentChange(val) {
      this.currentPage = val
      this.loading = true
      await this.getAdminUsers('changePage')
      this.loading = false
    },
    handleDelete(val) {
      let res
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        try {
          this.loading = true
          res = await Admin.deleteOneUser(val.row.id)
        } catch (e) {
          this.loading = false
          console.log(e)
        }
        if (res.error_code === 0) {
          this.loading = false
          if (this.total_nums % this.pageCount === 1 && this.currentPage !== 1) { // 判断删除的是不是每一页的最后一条数据
            this.currentPage--
          }
          await this.getAdminUsers()
          this.$message({
            type: 'success',
            message: `${res.msg}`,
          })
        } else {
          this.loading = false
          this.$message.error(`${res.msg}`)
        }
      })
    },
    // 提交表单信息
    async confirmEdit() {
      if (this.activeTab === '修改信息') {
        await this.$refs.userInfo.submitForm('form')
      } else {
        await this.$refs.password.submitForm('form')
      }
    },
    // 重置
    resetForm() {
      if (this.activeTab === '修改信息') {
        this.$refs.userInfo.resetForm('form')
      } else {
        this.$refs.password.resetForm('form')
      }
    },
    // 双击 table ro
    rowClick(row) {
      this.handleEdit(row)
    },
    // 弹框 右上角 X
    handleClose(done) {
      this.dialogFormVisible = false
      done()
    },
    // 切换tab栏
    handleClick(tab) {
      console.log(tab)
      this.activeTab = tab.name
    },
    // 监听子组件更新用户信息是否成功
    async handleInfoResult(flag) {
      this.dialogFormVisible = false
      if (flag === true) {
        this.getAdminUsers()
      }
    },
    // 监听子组件更新密码是否成功
    handlePasswordResult(result) {
      if (result === true) {
        this.dialogFormVisible = false
      }
    },
    // 监听添加用户是否成功
    async addUser(flag) {
      if (flag === true) {
        if (this.total_nums % this.pageCount === 0) { // 判断当前页的数据是不是满了，需要增加新的页码
          this.currentPage++
        }
        await this.getAdminUsers()
        this.refreshPagination = false // 刷新pagination组件
        this.$nextTick(() => {
          this.refreshPagination = true
        })
      }
    },
    // 获取省份列表
    async getProvinceAll() {
      this.provinceArr = await province.getProvinceAll()
    },
    // 获取城市列表
    async getCityAll() {
      this.cityArr = await city.getCityAll({ province_id: this.province_id })
    },
    // 获取区县列表
    async getCountyAll() {
      this.countyArr = await county.getCountyAll({ province_id: this.province_id, city_id: this.city_id })
    },
  },
  async created() {
    await this.getAdminUsers()
    this.getProvinceAll()
    this.getAllGroups()
    this.tableColumn = [
      { prop: 'username', label: '名称' },
      { prop: 'group_name', label: '所属分组' },
      { prop: 'province.name', label: '省份' },
      { prop: 'city.name', label: '城市' },
      { prop: 'county.name', label: '区/县' },
    ] // 设置表头信息
    this.operate = [{ name: '编辑', func: 'handleEdit', type: 'primary' }, { name: '删除', func: 'handleDelete', type: 'danger' }]
    this.eventBus.$on('addUser', this.addUser)
  },
  beforeDestroy() {
    this.eventBus.$off('addUser', this.addUser)
  },
}
</script>

<style lang="scss" scoped>
.container {
  padding: 0 30px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      height: 59px;
      line-height: 59px;
      color: $parent-title-color;
      font-size: 16px;
      font-weight: 500;
    }
  }

  .pagination {
    display: flex;
    justify-content: flex-end;
    margin: 20px;
  }
}

.info {
  margin-left: -55px;
  margin-bottom: -30px;
}

.password {
  margin-top: 20px;
  margin-left: -55px;
  margin-bottom: -20px;
}
</style>
